package com.guessdroid.labeling;

import java.util.ArrayList;
import com.guessdroid.util.AndroidWriter;
import com.guessdroid.util.Constants;

public class GContextList implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	public ArrayList<GContext> contexts;

	private int nextLabelId;

	private GContextList() {
		contexts = new ArrayList<GContext>();
		nextLabelId = 1;
	}

	public static GContextList read() {
		GContextList list;
		try {
			list = (GContextList) AndroidWriter
					.readObjectFromFile(Constants.CONTEXTS_FILE);
		} catch (ClassCastException ex) {
			list = null; // file not found or is corrupt
		}
		if (list == null) {
			list = new GContextList();
		}
		return list;
	}

	public void save() {
		AndroidWriter.writeObjectToFile(this, Constants.CONTEXTS_FILE);
	}

	public void addContext(String name) {
		contexts.add(new GContext(name, nextLabelId));
		nextLabelId++;
	}

	public String successPercent() {
		int correctCount = 0;
		int total = 0;
		for (GContext context : contexts) {
			correctCount += context.correctCount;
			total += (context.correctCount + context.wrongCount);
		}
		if (total == 0) {
			return "0";
		}
		int percent = (int) Math.round((double) correctCount / (double) total
				* 100);
		return Integer.toString(percent);

	}

	public void saveGuessResult(int id, boolean correct) {
		GContext context = findContextById(id);
		if (context != null) {
			if (correct) {
				context.correct();
			} else {
				context.wrong();
			}
			this.save();
		}
	}

	public GContext findContextById(int id) {
		for (GContext context : contexts) {
			if (context.id == id) {
				return context;
			}
		}
		return null;
	}

}
